package com.lagou.demo.service.intercepter;

import com.lagou.edu.mvcframework.annotations.LagouService;
import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.pojo.Handler;
import com.lagou.edu.mvcframework.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@LagouService
public class SecurityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = request.getParameter("username");
        Handler handler1 = (Handler)handler;
        Object controller = handler1.getController();
        Method method = handler1.getMethod();
        Security classAnnotation = controller.getClass().getAnnotation(Security.class);
        Security methodAnnotation = method.getAnnotation(Security.class);
        if (classAnnotation != null){
            if (username == null || username.isEmpty()){
                return reject(response);
            }
            if (!Arrays.asList(classAnnotation.value()).contains(username)){
                return reject(response);
            }
        }
        if (methodAnnotation != null){
            if (username == null || username.isEmpty()){
                return reject(response);
            }
            if (!Arrays.asList(methodAnnotation.value()).contains(username)){
                return reject(response);
            }
        }
        return true;
    }

    private boolean reject(HttpServletResponse response) {
        printUnAuthorizedResult(response);
        return false;
    }

    private void printUnAuthorizedResult(HttpServletResponse response){
        try {
            response.getWriter().println("UnAuthorized");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

